package com.jrx.anytxn.transaction.job.collection.step;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.config.FilePathsConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
@Service
public class CollectionFileListener implements JobExecutionListener {
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private FilePathsConfig filePathsConfig;


    @Override
    public void beforeJob(JobExecution jobExecution) {
        String filePath = filePathsConfig.getCollectionFilePath();
        String fileName = filePathsConfig.getFileName();
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
        Date bussinessDate = org.getNextProcessingDate();
        String toDay = DateUtils.format(bussinessDate, "yyyyMMdd");
        String collrctionPath = filePath + org.getTenantId() + File.separator + toDay + File.separator;
        String collectionFileName = "_" + toDay + "_" + fileName + ".txt";
        //删除文件
        deleteFile(collrctionPath, collectionFileName, TransBizConstant.COLLECTION_FILE_TYPE_CUSTOMER);
        deleteFile(collrctionPath, collectionFileName, TransBizConstant.COLLECTION_FILE_TYPE_CUSTOMER_ADDRESS);
        deleteFile(collrctionPath, collectionFileName, TransBizConstant.COLLECTION_FILE_TYPE_CUSTOMER_CONTACT);
        deleteFile(collrctionPath, collectionFileName, TransBizConstant.COLLECTION_FILE_TYPE_LOAN_MAIN);
        deleteFile(collrctionPath, collectionFileName, TransBizConstant.COLLECTION_FILE_TYPE_REPAYMENT_PLAN);

    }

    @Override
    public void afterJob(JobExecution jobExecution) {

    }

    /**
     * 删除文件
     * @param basePath
     * @param fileName
     * @param fileType
     */
    private static void deleteFile(String basePath, String fileName, String fileType) {
        //根据文件类型拼接完整文件名
        String fileHoleName = fileType + fileName;
        Path fPath = Paths.get(basePath + fileHoleName);
        //文件存在，删除文件
        if (fPath.toFile().exists()) {
            try {
                Files.delete(fPath);
            } catch (IOException e) {
                //因为listener实现的原接口未对异常做处理，所以不能抛出普通异常。
                throw new RuntimeException(e);
            }
        }

    }
}
